import React, { useState } from "react";
import { MdEditor, MdPreview } from "md-editor-rt";
import "md-editor-rt/lib/style.css";
import { useSelector } from "react-redux";
import { RootState } from "@/redux";
import styles from "./index.module.less";
import { useLocation } from "react-router-dom";
import { Button, Drawer } from "antd";
import BlogAdd from "../BlogAdd";
import { getBlogDetail } from "@/redux/modules/blog/action";

const Editor: React.FC = () => {
	const location = useLocation();
	const state: any = location.state;
	const blogDetail = useSelector((state: RootState) => state.blog.blogDetail);
	const [content_text, setContent_text] = useState(state?.id ? blogDetail.content_text : "");
	const [codeTheme] = useState("github");

	const [id] = useState("preview-only");

	const onSave = () => {
		console.log(content_text);
	};

	const [addVisible, setAddVisible] = useState(false);
	const onCloseAdd = () => {
		setAddVisible(false);
	};
	const [editVisible, setEditVisible] = useState(false);
	const openEdit = async (id: number) => {
		getBlogDetail(id);
		setEditVisible(true);
	};

	return (
		<div className={styles.root}>
			{!state?.id && <Button onClick={() => setAddVisible(true)}>新增</Button>}
			{state?.edit && <Button onClick={() => openEdit(state?.id)}>修改</Button>}

			{state?.id && !state?.edit ? (
				<MdPreview editorId={id} modelValue={content_text} codeTheme={codeTheme} previewTheme={codeTheme} />
			) : (
				<MdEditor
					modelValue={content_text}
					onChange={setContent_text}
					codeTheme={codeTheme}
					previewTheme={codeTheme}
					onSave={onSave}
				/>
			)}

			<Drawer
				title="新增"
				placement="right"
				width={500}
				onClose={() => {
					setAddVisible(false);
				}}
				visible={addVisible}
			>
				<BlogAdd onComfirm={onCloseAdd} content_text={content_text}></BlogAdd>
			</Drawer>

			<Drawer
				title="修改"
				placement="right"
				width={500}
				onClose={() => {
					setEditVisible(false);
				}}
				visible={editVisible}
			>
				<BlogAdd type="edit" onComfirm={onCloseAdd} content_text={content_text}></BlogAdd>
			</Drawer>
		</div>
	);
};

export default Editor;
